package transaction

import (
	"encoding/hex"

	"github.com/gogf/gf/frame/g"
	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric-protos-go/common"
	pb "github.com/hyperledger/fabric-protos-go/peer"
	putil "github.com/hyperledger/fabric/protoutil"
)

func getEndorsers(envelope *common.Envelope) ([]string, *string, error) {
	payload := &common.Payload{}
	err := proto.Unmarshal(envelope.Payload, payload)
	if err != nil {
		return nil, nil, err
	}
	transaction := &pb.Transaction{}
	err = proto.Unmarshal(payload.Data, transaction)
	if err != nil {
		return nil, nil, err
	}
	chaincodeActionPayload, _, err := putil.GetPayloads(transaction.Actions[0])
	if err != nil {
		return nil, nil, err
	}

	chaincodeEndorsedAction := chaincodeActionPayload.Action

	proposalResponsePayload := &pb.ProposalResponsePayload{}
	err = proto.Unmarshal(chaincodeEndorsedAction.ProposalResponsePayload, proposalResponsePayload)
	if err != nil {
		return nil, nil, err
	}
	proposalHash := hex.EncodeToString(proposalResponsePayload.ProposalHash)
	//g.Log().Infof("提案哈希: %v", proposalHash)

	//g.Dump(*chaincodeActionPayload)
	// 背书
	sArgs := make([]string, 0)
	for _, v := range chaincodeEndorsedAction.Endorsements {
		//g.Log().Infof("%d------------> %#v", k, v.Endorser)
		//g.Dump(v)

		//cert, err := GetX509CertByBytes(v.Endorser)
		//if err != nil {
		//g.Log().Errorf("抽取证书失败, %v", err)
		//return nil, err
		//}
		//g.Dump(cert)
		//g.Dump(cert.Subject)
		endorserName, err := GetEndorserNameByBytes(v.Endorser)
		if err != nil {
			g.Log().Errorf("抽取机构名称失败, %v", err)
			return nil, nil, err
		}
		sArgs = append(sArgs, *endorserName)
	}

	return sArgs, &proposalHash, nil
}
